import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'dart:typed_data';
import 'mediaGridItem.dart';

class MediaGrid extends StatefulWidget {
  final List<dynamic> mediaList; // AssetEntity
  final List<int> selectedIndexes; // 选中的索引
  final int maxSelect;
  final Function(int index) onTap;
  final bool isVideo;
  final ScrollController? scrollController;
  final int networkImageCount; // 添加网络图片数量参数

  const MediaGrid({
    Key? key,
    required this.mediaList,
    required this.selectedIndexes,
    required this.onTap,
    this.maxSelect = 18,
    this.isVideo = false,
    this.scrollController,
    this.networkImageCount = 0, // 默认值为0
  }) : super(key: key);

  @override
  State<MediaGrid> createState() => _MediaGridState();
}

class _MediaGridState extends State<MediaGrid>
    with AutomaticKeepAliveClientMixin {
  // 将静态缓存移到State类中
  static final Map<String, Uint8List> _thumbnailCache = {};

  @override
  bool get wantKeepAlive => true; // 保持状态不被销毁

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用，用于 AutomaticKeepAliveClientMixin

    return GridView.builder(
      controller: widget.scrollController,
      padding: EdgeInsets.zero,
      physics: ClampingScrollPhysics(), // 使用更平滑的滚动物理
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        crossAxisSpacing: 2,
        mainAxisSpacing: 2,
      ),
      itemCount: widget.mediaList.length,
      itemBuilder: (context, index) {
        try {
          final isSelected = widget.selectedIndexes.contains(index);
          final selectOrder = isSelected
              ? widget.selectedIndexes.indexOf(index) +
                  1 +
                  widget.networkImageCount // 添加网络图片偏移量
              : null;
          final isDisabled =
              !isSelected && widget.selectedIndexes.length >= widget.maxSelect;
          final AssetEntity entity = widget.mediaList[index];

          // 使用缓存的缩略图构建器
          Widget thumbnail = FutureBuilder<Uint8List?>(
            future: _getCachedThumbnail(entity),
            builder: (context, snapshot) {
              if (snapshot.hasError) {
                return Container(
                  color: Colors.red,
                  child: Center(child: Icon(Icons.error, color: Colors.white)),
                );
              }
              try {
                if (snapshot.connectionState == ConnectionState.done &&
                    snapshot.hasData &&
                    snapshot.data != null) {
                  return Image.memory(snapshot.data!,
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: double.infinity);
                } else {
                  return Container(color: Colors.grey[300]);
                }
              } catch (e, s) {
                return Container(
                  color: Colors.red,
                  child: Center(child: Icon(Icons.error, color: Colors.white)),
                );
              }
            },
          );
          String? duration;
          if (entity.type == AssetType.video) {
            final d = entity.videoDuration;
            duration = d != null ? _formatDuration(d) : null;
          }
          return MediaGridItem(
            key: ValueKey(entity.id),
            thumbnail: thumbnail,
            isSelected: isSelected,
            selectOrder: selectOrder,
            isDisabled: isDisabled,
            isVideo: entity.type == AssetType.video,
            duration: duration,
            onTap: () => widget.onTap(index),
          );
        } catch (e, s) {
          return Container(
            color: Colors.red,
            child: Center(child: Icon(Icons.error, color: Colors.white)),
          );
        }
      },
    );
  }

  String _formatDuration(Duration d) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(d.inMinutes.remainder(60));
    final seconds = twoDigits(d.inSeconds.remainder(60));
    return "${d.inHours > 0 ? '${twoDigits(d.inHours)}:' : ''}$minutes:$seconds";
  }

  Future<Uint8List?> _getCachedThumbnail(AssetEntity entity) async {
    final key = "${entity.id}_${ThumbnailSize(200, 200).toString()}";
    if (_thumbnailCache.containsKey(key)) {
      return _thumbnailCache[key];
    } else {
      final data = await entity.thumbnailDataWithSize(ThumbnailSize(200, 200));
      if (data != null) {
        _thumbnailCache[key] = data;
      }
      return data;
    }
  }
}

// 创建新的优化版MediaGrid
class OptimizedMediaGrid extends StatefulWidget {
  final List<dynamic> mediaList;
  final List<int> selectedIndexes;
  final Map<int, int> orderMap;
  final int maxSelect;
  final Function(int index) onTap;
  final bool isVideo;
  final int networkImageCount;
  final VoidCallback? onLoadMore;

  const OptimizedMediaGrid({
    Key? key,
    required this.mediaList,
    required this.selectedIndexes,
    required this.orderMap,
    required this.onTap,
    this.maxSelect = 18,
    this.isVideo = false,
    this.networkImageCount = 0,
    this.onLoadMore,
  }) : super(key: key);

  @override
  State<OptimizedMediaGrid> createState() => _OptimizedMediaGridState();
}

class _OptimizedMediaGridState extends State<OptimizedMediaGrid>
    with AutomaticKeepAliveClientMixin {
  // 缓存Future而不是数据，避免FutureBuilder重建
  static final Map<String, Future<Uint8List?>> _thumbnailCache = {};

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification scrollInfo) {
        if (widget.onLoadMore != null &&
            scrollInfo is ScrollEndNotification &&
            scrollInfo.metrics.pixels >=
                scrollInfo.metrics.maxScrollExtent - 200) {
          widget.onLoadMore!();
        }
        return false;
      },
      child: GridView.builder(
        padding: EdgeInsets.zero,
        physics: ClampingScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          crossAxisSpacing: 2,
          mainAxisSpacing: 2,
        ),
        itemCount: widget.mediaList.length,
        itemBuilder: (context, index) {
          try {
            final isSelected = widget.selectedIndexes.contains(index);
            final selectOrder = widget.orderMap[index];
            // 修改 isDisabled 判断逻辑，考虑网络图片数量
            final isDisabled = !isSelected &&
                (widget.networkImageCount + widget.selectedIndexes.length >=
                    widget.maxSelect);
            final AssetEntity entity = widget.mediaList[index];

            Widget thumbnail = FutureBuilder<Uint8List?>(
              future: _getCachedThumbnail(entity), // 返回缓存的Future实例
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  return Container(
                    color: Colors.red,
                    child:
                        Center(child: Icon(Icons.error, color: Colors.white)),
                  );
                }
                try {
                  if (snapshot.connectionState == ConnectionState.done &&
                      snapshot.hasData &&
                      snapshot.data != null) {
                    return Image.memory(
                      snapshot.data!,
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: double.infinity,
                      gaplessPlayback: true, // 减少闪烁
                    );
                  } else {
                    return Container(color: Colors.grey[300]);
                  }
                } catch (e, s) {
                  return Container(
                    color: Colors.red,
                    child:
                        Center(child: Icon(Icons.error, color: Colors.white)),
                  );
                }
              },
            );

            String? duration;
            if (entity.type == AssetType.video) {
              final d = entity.videoDuration;
              duration = d != null ? _formatDuration(d) : null;
            }

            return RepaintBoundary(
              child: MediaGridItem(
                key: ValueKey(entity.id), // 使用稳定的key，避免不必要的重建
                thumbnail: thumbnail,
                isSelected: isSelected,
                selectOrder: selectOrder,
                isDisabled: isDisabled, // 传递正确的 disabled 状态
                isVideo: entity.type == AssetType.video,
                duration: duration,
                onTap: () => widget.onTap(index),
              ),
            );
          } catch (e, s) {
            return Container(
              color: Colors.red,
              child: Center(child: Icon(Icons.error, color: Colors.white)),
            );
          }
        },
      ),
    );
  }

  String _formatDuration(Duration d) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(d.inMinutes.remainder(60));
    final seconds = twoDigits(d.inSeconds.remainder(60));
    return "${d.inHours > 0 ? '${twoDigits(d.inHours)}:' : ''}$minutes:$seconds";
  }

  // 关键优化：缓存Future实例而不是数据
  Future<Uint8List?> _getCachedThumbnail(AssetEntity entity) {
    final key = "${entity.id}_${ThumbnailSize(200, 200).toString()}";

    if (_thumbnailCache.containsKey(key)) {
      return _thumbnailCache[key]!; // 返回同一个Future实例
    } else {
      final future = entity.thumbnailDataWithSize(ThumbnailSize(200, 200));
      _thumbnailCache[key] = future; // 缓存Future而不是结果
      return future;
    }
  }
}
